import requests
import json
import yaml
import os
from datetime import datetime
from loguru import logger


def load_config():
    """
    加载配置文件
    """
    current_dir = os.path.dirname(os.path.abspath(__file__))
    config_path = os.path.join(os.path.dirname(current_dir), 'config', 'config.yaml')
    with open(config_path, encoding='utf-8') as f:
        return yaml.safe_load(f)


class WeChatWorkBot:
    """
    企业微信机器人消息发送类
    """
    
    def __init__(self, webhook_key=None):
        """
        初始化企业微信机器人
        
        Args:
            webhook_key: 机器人webhook的key，如果不提供则从配置文件读取
        """
        if webhook_key:
            self.webhook_key = webhook_key
        else:
            config = load_config()
            self.webhook_key = config.get('wechat_work', {}).get('webhook_key')
            
        if not self.webhook_key:
            raise ValueError("企业微信机器人webhook_key未配置")
            
        self.webhook_url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={self.webhook_key}"
    
    def send_text(self, content, mentioned_list=None, mentioned_mobile_list=None):
        """
        发送文本消息
        
        Args:
            content: 消息内容
            mentioned_list: @的用户userid列表
            mentioned_mobile_list: @的用户手机号列表
            
        Returns:
            bool: 发送是否成功
        """
        data = {
            "msgtype": "text",
            "text": {
                "content": content
            }
        }
        
        if mentioned_list or mentioned_mobile_list:
            data["text"]["mentioned_list"] = mentioned_list or []
            data["text"]["mentioned_mobile_list"] = mentioned_mobile_list or []
            
        return self._send_message(data)
    
    def send_markdown(self, content):
        """
        发送markdown消息
        
        Args:
            content: markdown格式的消息内容
            
        Returns:
            bool: 发送是否成功
        """
        data = {
            "msgtype": "markdown",
            "markdown": {
                "content": content
            }
        }
        
        return self._send_message(data)
    
    def send_news(self, articles):
        """
        发送图文消息
        
        Args:
            articles: 图文消息列表，每个元素包含title、description、url、picurl
            
        Returns:
            bool: 发送是否成功
        """
        data = {
            "msgtype": "news",
            "news": {
                "articles": articles
            }
        }
        
        return self._send_message(data)
    
    def send_file(self, media_id):
        """
        发送文件消息
        
        Args:
            media_id: 文件的media_id
            
        Returns:
            bool: 发送是否成功
        """
        data = {
            "msgtype": "file",
            "file": {
                "media_id": media_id
            }
        }
        
        return self._send_message(data)
    
    def _send_message(self, data):
        """
        发送消息的内部方法
        
        Args:
            data: 消息数据
            
        Returns:
            bool: 发送是否成功
        """
        try:
            headers = {
                'Content-Type': 'application/json'
            }
            
            response = requests.post(
                self.webhook_url,
                data=json.dumps(data, ensure_ascii=False).encode('utf-8'),
                headers=headers,
                timeout=10
            )
            
            result = response.json()
            
            if result.get('errcode') == 0:
                logger.info("企业微信消息发送成功")
                return True
            else:
                logger.error(f"企业微信消息发送失败: {result.get('errmsg')}")
                return False
                
        except Exception as e:
            logger.error(f"企业微信消息发送异常: {str(e)}")
            return False


def send_sync_notification(success_count=0, error_count=0, error_details=None):
    """
    发送同步任务通知
    
    Args:
        success_count: 成功数量
        error_count: 错误数量
        error_details: 错误详情列表
    """
    try:
        bot = WeChatWorkBot()
        
        # 构建消息内容
        if error_count == 0:
            content = f"✅ **数据同步完成**\n\n" \
                     f"📊 **同步统计**\n" \
                     f"- 成功: {success_count} 条\n" \
                     f"- 失败: {error_count} 条\n\n" \
                     f"🕐 **完成时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        else:
            content = f"⚠️ **数据同步完成(有错误)**\n\n" \
                     f"📊 **同步统计**\n" \
                     f"- 成功: {success_count} 条\n" \
                     f"- 失败: {error_count} 条\n\n"
            
            if error_details:
                content += f"❌ **错误详情**\n"
                for i, error in enumerate(error_details[:5], 1):  # 最多显示5个错误
                    content += f"{i}. {error}\n"
                if len(error_details) > 5:
                    content += f"... 还有 {len(error_details) - 5} 个错误\n"
            
            content += f"\n🕐 **完成时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        
        bot.send_markdown(content)
        
    except Exception as e:
        logger.error(f"发送企业微信通知失败: {str(e)}")


def send_error_alert(error_message, task_name="数据同步"):
    """
    发送错误告警
    
    Args:
        error_message: 错误信息
        task_name: 任务名称
    """
    try:
        bot = WeChatWorkBot()
        
        content = f"🚨 **{task_name}异常告警**\n\n" \
                 f"❌ **错误信息**: {error_message}\n\n" \
                 f"🕐 **发生时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n" \
                 f"请及时处理！"
        
        bot.send_markdown(content)
        
    except Exception as e:
        logger.error(f"发送企业微信错误告警失败: {str(e)}")


def send_custom_message(message, msg_type="text", **kwargs):
    """
    发送自定义消息
    
    Args:
        message: 消息内容
        msg_type: 消息类型 (text, markdown, news, file)
        **kwargs: 其他参数
    """
    try:
        bot = WeChatWorkBot()
        
        if msg_type == "text":
            return bot.send_text(message, **kwargs)
        elif msg_type == "markdown":
            return bot.send_markdown(message)
        elif msg_type == "news":
            return bot.send_news(message)
        elif msg_type == "file":
            return bot.send_file(message)
        else:
            logger.error(f"不支持的消息类型: {msg_type}")
            return False
            
    except Exception as e:
        logger.error(f"发送自定义消息失败: {str(e)}")
        return False